package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.health.dao.PermissionDao;
import com.itheima.health.dao.RoleDao;
import com.itheima.health.dao.UserDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.entity.QueryPageBean;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author zhangmeng
 * @description 用户服务实现类
 * @date 2019/9/6
 **/
@Slf4j
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        //先查基本信息
        User user = userDao.selectByUsername(username);
        if (null == user) {
            //用户不存在
            return null;
        }
        //根据用户ID查角色信息
        List<Role> roles = roleDao.selectByUserId(user.getId());
        for (Role role : roles) {
            //根据角色ID查权限信息
            List<Permission> permissions = permissionDao.selectByRoleId(role.getId());
            role.getPermissions().addAll(permissions);
        }
        user.getRoles().addAll(roles);
        return user;
    }

    @Transactional
    @Override
    public void add(Integer[] roleIds, User user) {
        log.info("[用户-新增]roleIds:{},user:{}",roleIds,user);

        PasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(user.getPassword()));


        userDao.insert(user);

        if (user.getId()!=null && roleIds!=null&&roleIds.length>0) {
            for (Integer roleId : roleIds) {
                userDao.insertRole2User(roleId, user.getId());
            }
        }
    }

    @Transactional
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        log.info("[用户-分页]queryPageBean:{}",queryPageBean);
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<User> page =userDao.findByPage(queryPageBean.getQueryString());

        List<User> users = page.getResult();
        for (User user : users) {
            user.setPassword("************");
        }
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public User findById(Integer id) {
        return userDao.findById(id);
    }

    @Override
    public List<Integer> findroleIdsByuserId(Integer id) {
        return userDao.findroleIdsByuserId(id);
    }

    @Transactional
    @Override
    public void edit(Integer[] roleIds, User user) {
        log.info("[用户-编辑]roleIds:{},user:{}",roleIds,user);

        PasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        userDao.edit(user);

        userDao.deleteRelationByUserId(user.getId());

        for (Integer roleId : roleIds) {

            userDao.insertRole2User(roleId,user.getId());
        }




    }

    @Override
    public void delById(Integer id) {

        long count=userDao.countRoleByUserId(id);
        if (count>=1){
            throw new BusinessRuntimeException("该用户是大角色,不能删");
        }
        userDao.deleteRelationByUserId(id);
        userDao.deleteById(id);

    }


}
